/*
 * =====================================================================================
 *
 *       Filename:  index_table.cpp
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  04/02/2011 09:34:34 PM
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Chen Ken (Ken), zlchen.ken@gmail.com
 *        Company:  EMC
 *
 * =====================================================================================
 */

#include <iostream>
#include <vector>
#include <algorithm>

template<class T, class U>
struct ComparePair1stDeref
{
	bool operator()(const std::pair<T, U>& lhs, const std::pair<T, U>& rhs) const
	{
	  return *lhs.first < *rhs.first;
	} 
};

template<class IterIn, class IterOut>
void sort_idxtbl(IterIn first, IterIn last, IterOut out)
{
	std::vector<std::pair<IterIn, int> > s(last - first);
	for(int i = 0; i < s.size(); ++i)
	{
	  s[i] = std::make_pair(first + i, i);
	}
	std::sort(s.begin(), s.end(), ComparePair1stDeref<IterIn, int>());
	for(int j = 0; j < s.size(); ++j, ++out)
	{
	  *out = s[j].second;
	}
}

int main(int argc, char* argv[])
{
	int ai[10] = {15,12,13,14,18,11,10,17,16,19};
	std::vector<int> idxtbl(10);
	sort_idxtbl(ai, ai + 10, idxtbl.begin());
	for(int i = 0; i < 10; ++i)
	{
		std::cout << "i=" << i
			<< ", idxtbl[i]=" << idxtbl[i]
			<< ",ai[idxtbl[i]]=" << ai[idxtbl[i]]
			<< std::endl;
	}
}

